import React, { useEffect, useState } from 'react';
import { Calendar, Badge, Card, Typography, Modal, Spin, message } from 'antd';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { getDailySentenceList } from '@/services/learningContentApi';

const { Title } = Typography;

interface SentenceCalendarProps {
  sentences?: LEARNING.DailySentenceModel[];
  onDateSelect?: (date: Dayjs) => void;
  visible?: boolean;
  onCancel?: () => void;
  onSuccess?: () => void;
}

const SentenceCalendar: React.FC<SentenceCalendarProps> = ({
  sentences: propSentences,
  onDateSelect,
  visible,
  onCancel,
  onSuccess,
}) => {
  const [sentences, setSentences] = useState<LEARNING.DailySentenceModel[]>(propSentences || []);
  const [loading, setLoading] = useState(false);

  // 获取句子数据
  const fetchSentences = async () => {
    try {
      setLoading(true);
      // 分页获取所有数据
      let allSentences: LEARNING.DailySentenceModel[] = [];
      let page = 1;
      const limit = 100; // 使用最大允许的每页数量

      while (true) {
        const response = await getDailySentenceList({
          page,
          limit,
        });

        if (response.code === 200) {
          allSentences = [...allSentences, ...response.data.list];

          // 如果当前页数据少于limit，说明已经是最后一页
          if (response.data.list.length < limit) {
            break;
          }
          page++;
        } else {
          break;
        }
      }

      setSentences(allSentences);
    } catch (error) {
      message.error('获取句子数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible && !propSentences) {
      fetchSentences();
    }
  }, [visible, propSentences]);

  // 根据日期获取句子数据
  const getSentenceByDate = (date: Dayjs) => {
    if (!sentences || sentences.length === 0) return null;

    const dateStr = date.format('YYYY-MM-DD');
    return sentences.find(sentence => {
      if (!sentence.date) return false;
      return dayjs(sentence.date).format('YYYY-MM-DD') === dateStr;
    });
  };

  // 日期单元格渲染
  const dateCellRender = (value: Dayjs) => {
    const sentence = getSentenceByDate(value);
    if (!sentence) return null;

    const getStatusColor = (isActive: boolean) => {
      return isActive ? 'success' : 'default';
    };

    // 获取显示文本
    const displayText = sentence.chinese?.substring(0, 10) || '句子';

    return (
      <div style={{ fontSize: '12px' }}>
        <Badge
          status={getStatusColor(sentence.is_active)}
          text={displayText}
        />
      </div>
    );
  };

  // 月份单元格渲染
  const monthCellRender = (value: Dayjs) => {
    if (!sentences || sentences.length === 0) return null;

    const monthSentences = sentences.filter(sentence =>
      sentence.date && dayjs(sentence.date).isSame(value, 'month')
    );

    if (monthSentences.length === 0) return null;

    return (
      <div style={{ fontSize: '12px', textAlign: 'center' }}>
        <div>共 {monthSentences.length} 句</div>
      </div>
    );
  };

  const handleSelect = (date: Dayjs) => {
    onDateSelect?.(date);
  };

  const calendarContent = (
    <Spin spinning={loading}>
      <Calendar
        cellRender={(current, info) => {
          if (info.type === 'date') {
            return dateCellRender(current);
          }
          if (info.type === 'month') {
            return monthCellRender(current);
          }
          return null;
        }}
        onSelect={handleSelect}
        style={{ border: '1px solid #f0f0f0', borderRadius: '6px' }}
      />
      <div style={{ marginTop: 16, fontSize: '12px', color: '#666' }}>
        <Badge status="success" text="已启用" style={{ marginRight: 16 }} />
        <Badge status="default" text="已禁用" />
      </div>
    </Spin>
  );

  // 如果是弹窗模式
  if (visible !== undefined) {
    return (
      <Modal
        title="每日一句日历"
        open={visible}
        onCancel={onCancel}
        footer={null}
        width={800}
      >
        {calendarContent}
      </Modal>
    );
  }

  // 如果是嵌入模式
  return (
    <Card>
      <Title level={4} style={{ marginBottom: 16 }}>
        每日一句日历
      </Title>
      {calendarContent}
    </Card>
  );
};

export default SentenceCalendar;
